/*===========================================================================
  Copyright (C) 2013 by the Okapi Framework contributors
-----------------------------------------------------------------------------
  This library is free software; you can redistribute it and/or modify it 
  under the terms of the GNU Lesser General Public License as published by 
  the Free Software Foundation; either version 2.1 of the License, or (at 
  your option) any later version.

  This library is distributed in the hope that it will be useful, but 
  WITHOUT ANY WARRANTY; without even the implied warranty of 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
  General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License 
  along with this library; if not, write to the Free Software Foundation, 
  Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

  See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/

package net.sf.okapi.lib.omegat;

import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

import net.sf.okapi.common.Util;
import net.sf.okapi.common.filters.FilterConfigurationMapper;

public class DefaultOptions extends JDialog {
	
	private static final long serialVersionUID = 1L;
	
	private final Map<String, String> options;
	final JRadioButton rdDefault;
	final JRadioButton rdCustom;
	final JTextField edPath;
	final JButton btGetPath;

	// Internal class for the option actions
	class OptionsListener implements ActionListener {
		@Override
		public void actionPerformed (ActionEvent event) {
			edPath.setEnabled(rdCustom.isSelected());
			btGetPath.setEnabled(rdCustom.isSelected());
		}
	}
	
	/**
	 * Creates a DefaultOptions object.
	 * @param parent the parent dialog.
	 * @param paramOptions the options.
	 */
	public DefaultOptions (final Dialog parent,
		final Map<String, String> paramOptions,
		final String defaultConfigId)
	{
		super(parent, "Okapi Filter Options", true);
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

		if ( paramOptions == null ) {
			this.options = new HashMap<String, String>();
		}
		else {
			this.options = paramOptions;
		}

		Container cp = getContentPane();
	    cp.setLayout(new GridBagLayout());

	    OptionsListener optListner = new OptionsListener();
	    
		rdDefault = new JRadioButton(String.format("Use the default filter settings (%s)", defaultConfigId));
		rdDefault.addActionListener(optListner);
        GridBagConstraints c = new GridBagConstraints();
        c.anchor = GridBagConstraints.FIRST_LINE_START;
        c.gridx = 0; c.gridwidth = 3;
        c.gridy = 0;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(10, 10, 0, 10);
    	cp.add(rdDefault, c);

		rdCustom = new JRadioButton("Use the follwing filter parameters file:");
		rdCustom.addActionListener(optListner);
        c = new GridBagConstraints();
        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 0; c.gridwidth = 3;
        c.gridy = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 10, 0, 10);
    	cp.add(rdCustom, c);
		
    	ButtonGroup grpOptions = new ButtonGroup();
    	grpOptions.add(rdDefault);
    	grpOptions.add(rdCustom);
		String path = options.get(AbstractOkapiFilter.USE_CUSTOM);
    	String def = options.get(AbstractOkapiFilter.USE_DEFAULT);
    	if (( def == null ) || !def.equals(AbstractOkapiFilter.USE_DEFAULT_YES) ) {
    		if ( Util.isEmpty(path) ) rdDefault.setSelected(true);
    		else rdCustom.setSelected(true);
    	}
    	else {
    		rdDefault.setSelected(true);
    	}
    	
    	final JPanel pnlPath = new JPanel(new GridBagLayout());
    	
    	edPath = new JTextField();
        c = new GridBagConstraints();
        c.anchor = GridBagConstraints.LINE_START;
        c.gridx = 0;
        c.gridy = 0;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;
        //c.insets = new Insets(0, 10, 5, 0);
    	pnlPath.add(edPath, c);
		if ( !Util.isEmpty(path) ) edPath.setText(path);
    	
	    btGetPath = new JButton("...");
	    btGetPath.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		JFileChooser dlg = new JFileChooser();
	    		dlg.setDialogTitle("Select a Filter Parameters File");
	    		dlg.setFileFilter(new FileNameExtensionFilter(
	    			"Filter Parameters Files (*"+FilterConfigurationMapper.CONFIGFILE_EXT+")",
	    			FilterConfigurationMapper.CONFIGFILE_EXT.substring(1)));
	    		String path = edPath.getText();
	    		if ( !Util.isEmpty(path) ) {
	    			dlg.setSelectedFile(new File(path));
	    		}
	    		if ( dlg.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ) {
	    			edPath.setText(dlg.getSelectedFile().getAbsolutePath());
	    		}
	    	}
	    });
        c = new GridBagConstraints();
        c.anchor = GridBagConstraints.LINE_END;
        c.gridx = 1;
        c.gridy = 0;
        c.insets = new Insets(0, 5, 0, 0);
	    pnlPath.add(btGetPath, c);
	    
	    c = new GridBagConstraints();
	    c.anchor = GridBagConstraints.LINE_START;
	    c.gridx = 0; c.gridwidth = 3;
	    c.gridy = 2;
	    c.fill = GridBagConstraints.HORIZONTAL;
	    c.weightx = 1.0;
	    c.insets = new Insets(0, 10, 5, 10);
	    cp.add(pnlPath, c);

    	// Do the actions for the options
    	optListner.actionPerformed(null);

    	final JPanel pnlAction = new JPanel(new GridLayout(1, 2, 5, 0));
	    
	    final JButton btOK = new JButton("OK");
	    btOK.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		// Set the default to yes if it's selected
	    		if ( rdDefault.isSelected() ) {
	    			paramOptions.put(AbstractOkapiFilter.USE_DEFAULT, AbstractOkapiFilter.USE_DEFAULT_YES);
	    		}
	    		// Then look at the path 
	    		String path = edPath.getText();
	    		if ( rdCustom.isSelected() ) {
	    			// It must not be empty to use that option
	    			if ( Util.isEmpty(path) ) {
	    				// Must not be empty
	    				JOptionPane.showMessageDialog(parent, "You must specify a path.", "Missing Path", JOptionPane.ERROR_MESSAGE);
	    				edPath.requestFocusInWindow();
	    				return;
	    			}
	    			// Use custom path
    				paramOptions.put(AbstractOkapiFilter.USE_DEFAULT, AbstractOkapiFilter.USE_DEFAULT_NO);
	    		}
	    		// Save the path (empty or not in all options)
    			paramOptions.put(AbstractOkapiFilter.USE_CUSTOM, path);
    			dispose();
	    	}
	    });
	    pnlAction.add(btOK);

    	final JButton btCancel = new JButton("Cancel");
	    btCancel.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		dispose();
	    	}
	    });
	    pnlAction.add(btCancel);
	    
	    c = new GridBagConstraints();
	    c.anchor = GridBagConstraints.LINE_END;
	    c.gridx = 0; c.gridwidth = 3;
	    c.gridy = 3;
	    c.insets = new Insets(0, 10, 10, 10);
	    cp.add(pnlAction, c);

	    pack();
	    setMinimumSize(new Dimension(600, getSize().height));
	    setMaximumSize(new Dimension(600, getSize().height));

        // Center the dialog
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((dim.width-getSize().width)/2, (dim.height-getSize().height)/2);

        // Set the focus properly
    	if ( rdDefault.isSelected() ) rdDefault.requestFocusInWindow();
    	else rdCustom.requestFocusInWindow();
	}
	
	/**
	 * Gets the options.
	 * @return a map of option key-value pairs, never null.
	 */
	public Map<String, String> getOptions () {
		return options;
	}

}
